import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select, Icon, Button, Modal, message, Badge, Divider, Tag, DatePicker, InputNumber,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './Order.less';

import { CSVLink, CSVDownload } from 'react-csv';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['error', 'success'];
const status = ["待支付", "已支付", "交易成功", "用户已取消", "退款中", "已退款", "交易关闭", "已退货"];
var _ = require('lodash');

@connect(({ order, loading }) => ({
  order,
  pagination: order.pagination,
  franList: order.franList,
  loading: loading.models.order,
}))
@Form.create()
export default class Order extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],

    csvData: [],

    headers: [{ label: '订单号', key: 'ordersId' }, { label: '下单时间', key: 'createTime' }, { label: '加盟商', key: 'franName' },
    { label: '商品名称', key: 'goodsName' }, { label: '交易状态', key: 'ordersSts' },
    { label: '订单类型', key: 'ordersType' }, { label: '订单金额', key: 'payCash' }, { label: '手机号', key: 'userPhone' }],


    startTime: null,
    endTime: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/fetchOrderList',
      payload: { "pageNum": "1", "pageSize": "10" }
    });

    dispatch({
      type: 'order/fetchFranList',
      payload: { "pageNum": "0", "pageSize": "0" }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    // console.log('分页条件', this.props.form.getFieldValue())

    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
      startTime: this.state.startTime ? this.state.startTime.format('YYYY-MM-DD HH:mm:mm') : null,
      endTime: this.state.endTime ? this.state.endTime.format('YYYY-MM-DD HH:mm:mm') : null,
    };

    dispatch({
      type: 'order/fetchOrderList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();

    this.setState({ startTime: null, endTime: null })

    dispatch({
      type: 'order/fetchOrderList',
      payload: {
        pageNum: 1,
        pageSize: this.props.pagination.pageSize ? this.props.pagination.pageSize : 10,
      },
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
    let data = [];
    if (rows && (rows.length > 0)) {
      for (let i = 0; i < rows.length; i++) {
        let oneRow = _.cloneDeep(rows[i]);

        if (oneRow.ordersSts == "0") {
          oneRow.ordersSts = '待支付'
        }
        if (oneRow.ordersSts == "1") {
          oneRow.ordersSts = '已支付'
        }
        if (oneRow.ordersSts == "2") {
          oneRow.ordersSts = '交易成功'
        }
        if (oneRow.ordersSts == "3") {
          oneRow.ordersSts = '用户已取消'
        }
        if (oneRow.ordersSts == "4") {
          oneRow.ordersSts = '退款中'
        }
        if (oneRow.ordersSts == "5") {
          oneRow.ordersSts = '已退款'
        }
        if (oneRow.ordersSts == "6") {
          oneRow.ordersSts = '交易关闭'
        }
        if (oneRow.ordersSts == "7") {
          oneRow.ordersSts = '已退货'
        }

        if (oneRow.ordersType == "0") {
          oneRow.ordersType = '课程'
        }
        if (oneRow.ordersType == "1") {
          oneRow.ordersType = '绘本'
        }
        if (oneRow.ordersType == "2") {
          oneRow.ordersType = '积分'
        }

        data.push(oneRow)
      }
    }

    this.setState({
      csvData: data,
    });
  };

  handleSearch() {
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      delete fieldsValue.time;

      const values = {
        ...fieldsValue,
        startTime: this.state.startTime ? this.state.startTime.format('YYYY-MM-DD HH:mm:mm') : null,
        endTime: this.state.endTime ? this.state.endTime.format('YYYY-MM-DD HH:mm:mm') : null,
        pageNum: 1,
        pageSize: this.props.pagination.pageSize ? this.props.pagination.pageSize : 10,
      };

      dispatch({
        type: 'order/fetchOrderList',
        payload: values,
      });
    });
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;



    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="订单号">
              {getFieldDecorator('ordersId')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="商品名称">
              {getFieldDecorator('goodsName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.handleSearch()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  _renderFran() {
    let options = '<Option value="undefined">全部</Option>'
    if (this.props.franList && (this.props.franList.length > 0))
      for (let i = 0; i < this.props.franList.length; i++) {
        options += <Option value={'' + this.props.franList[i].franId}>{this.props.franList[i].franName}</Option>
      }
    return options;
  }

  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="订单号">
              {getFieldDecorator('ordersId')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="商品名称">
              {getFieldDecorator('goodsName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('userPhone')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="订单类型">
              {getFieldDecorator('ordersType', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="0">课程</Option>
                  <Option value="1">绘本</Option>
                  <Option value="2">积分</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="订单状态">
              {getFieldDecorator('ordersSts', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="0">待支付</Option>
                  <Option value="1">已支付</Option>
                  <Option value="2">交易成功</Option>
                  <Option value="3">用户已取消</Option>
                  <Option value="4">退款中</Option>
                  <Option value="5">已退款</Option>
                  <Option value="6">交易关闭</Option>
                  <Option value="7">已退货</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="加盟商">
              {getFieldDecorator('franId', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  {(this.props.franList && this.props.franList.length > 0) && this.props.franList.map((item, i) => <Option key={i} value={'' + item.franId}>{item.franName}</Option>)}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="订单金额">
              {getFieldDecorator('minPayCash')(<InputNumber />)}
              {'-'}
              {getFieldDecorator('maxPayCash')(<InputNumber />)}
            </FormItem>
          </Col>
          <Col md={16} sm={24}>
            <FormItem label="下单时间">
              {getFieldDecorator('startTime')(
                <DatePicker
                  disabledDate={this.disabledStartDate}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择"
                  onChange={this.onStartChange}
                />
              )}
              --
            {/* </FormItem>
            <FormItem label="注册结束时间"> */}
              {getFieldDecorator('endTime')(
                <DatePicker
                  disabledDate={this.disabledEndDate}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择"
                  onChange={this.onEndChange}
                />
              )}
            </FormItem>
          </Col>
        </Row>

        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit" onClick={() => this.handleSearch()}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </span>
        </div>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  disabledStartDate = (startTime) => {
    const endTime = this.state.endTime;
    if (!startTime || !endTime) {
      return false;
    }
    return startTime.valueOf() > endTime.valueOf();
  }

  disabledEndDate = (endTime) => {
    const startTime = this.state.startTime;
    if (!endTime || !startTime) {
      return false;
    }
    return endTime.valueOf() <= startTime.valueOf();
  }

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  }

  onStartChange = (value) => {
    this.onChange('startTime', value);
  }

  onEndChange = (value) => {
    this.onChange('endTime', value);
  }

  render() {
    const tableData = {}
    tableData['list'] = this.props.order.orderList;
    tableData['pagination'] = this.props.order.pagination;

    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '订单号',
        dataIndex: 'ordersId',
        key: 'ordersId',
      },
      {
        title: '商品名称',
        dataIndex: 'goodsName',
        key: 'goodsName',
      },
      {
        title: '订单类型',
        dataIndex: 'ordersType',
        key: 'ordersType',
        render(val) {
          return <span>{val == '0' ? '课程' : val == '1' ? '绘本' : val == '2' ? '积分' : '其他'}</span>;
        },
      },
      {
        title: '手机号',
        dataIndex: 'userPhone',
        key: 'userPhone',
      },
      {
        title: '加盟商',
        dataIndex: 'franName',
        key: 'franName',
      },
      {
        title: '交易状态',
        dataIndex: 'ordersSts',
        key: 'ordersSts',
        render(val) {
          return status[val]
        },
      },
      {
        title: '订单金额',
        dataIndex: 'payCash',
        key: 'payCash',
        render(val) {
          return <span>{val.toFixed(2)}</span>;
        },
      },
      {
        title: '下单时间',
        dataIndex: 'createTime',
      },
      {
        title: '操作',
        key: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/order/detail/' + record.ordersId }))}>查看</a>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button type="primary">
                <CSVLink data={this.state.csvData} headers={this.state.headers} filename={"订单.csv"}>导出订单</CSVLink>
              </Button>
            </div>
            <StandardTable
              rowKey="ordersId"
              selectedRows={selectedRows}
              loading={this.props.loading}
              data={tableData}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
